<template>
  <div class="app-container">
    <el-button @click="downTemplate" type="primary" size="small">模板下载</el-button>

    <el-row class="upload-con">
      <el-col :span="4">
        <el-upload
          ref="xlsUpload"
          class="upload-subject"
          :action="importExcelPath"
          multiple
          :limit="1"
          :on-exceed="handleExceed"
          accept=".xls"
          :auto-upload="false"
          :before-upload="uploadXLSBefore"
          :on-success="uploadSuccess"
          :on-error="uploadError"

        >
          <el-button size="small" type="primary">添加Excel文件</el-button>
        </el-upload>
      </el-col>
      <el-col :span="4">
        <el-button size="small" type="info" @click="uploadXLS" :disabled="uploadButtonDisable">上传文件</el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script>
  export default {
    name: 'SubjectImport',
    data:function() {

      return {
        subjectExcelTemplate:'https://image-online-education.oss-cn-hangzhou.aliyuncs.com/excel/%E8%AF%BE%E7%A8%8B%E5%88%86%E7%B1%BB%E5%88%97%E8%A1%A8%E6%A8%A1%E6%9D%BF.xls',
        importExcelPath: 'http://127.0.0.1:8001/admin/education/subject/import-subject',
        uploadButtonDisable:false,
        loading: null,
      }
    },
    methods:{

      downTemplate(){

        window.open(this.subjectExcelTemplate,'_self');

      },
      handleExceed() {

        this.$message.warning("只能同时上传一个文件");
      },
      uploadXLS(){

        if (this.$refs.xlsUpload.uploadFiles.length > 0){

          this.$refs.xlsUpload.submit();
        } else {

          this.$message.warning("请选择上传的文件");
        }

      },
      uploadXLSBefore(){

        this.loading = this.$loading({
          lock: true,
          text: '上传图片中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });

        this.uploadButtonDisable = true;

      },
      uploadSuccess(response, file, fileList){

        if (this.loading != null){

          this.loading.close();
          this.loading = null;
        }

        if (response.code != 0){

          this.$message.error(response.message);
        }else {

          this.$message.success("文件上传成功");
          //清除待上传文件
          this.$refs.xlsUpload.clearFiles();
        }

        this.uploadButtonDisable = false;
      },
      uploadError(err, file, fileList){

        if (this.loading != null){

          this.loading.close();
          this.loading = null;
        }

        this.$message.error("文件上传失败")

        this.uploadButtonDisable = false;
      }
    }
  }
</script>

<style scoped>

  .upload-con{

    margin-top: 20px;
  }
</style>
